import { defineStore } from 'pinia'


export const useMenuStore = defineStore('menu', {
  state: () => ({ 
    isCollapse: false,
    selectMenu:[],
    routeList:[],
    adminData: JSON.parse(localStorage.getItem('pz_userInfo')) || null // 初始化时直接读取
  }),
  
  getters: {
    // 如果需要一个 getter 来返回 isCollapse 的状态
    isMenuCollapsed: (state) => state.isCollapse,
    // 或者返回一个反转状态（但不会修改原状态）
    isMenuExpanded: (state) => !state.isCollapse,
    // Getter 应该只返回数据，不修改状态
    getAdminData: (state) => state.adminData,
  },
  
  actions: {
    toggleCollapse() {
      // 直接通过 this 访问 state
      this.isCollapse = !this.isCollapse
    },

    SelectMenu(payload){
      if (this.selectMenu.findIndex(item => item.path === payload.path) === -1) {
        this.selectMenu.push(payload)
      }
    },

    CloseMenu(payload){
      const index = this.selectMenu.findIndex(val => val.name === payload.name)
      this.selectMenu.splice(index,1)
    },

    ChangRouter(payload){
      const modules = import.meta.glob('../views/**/**/*.vue');
      function RouterDigui(router) {
        router.forEach(route => {
          if (!route.children) {
            const url = `../views${route.meta.path}/index.vue`;
            route.component = modules[url];
          }else{
            RouterDigui(route.children);
          }
        });
      }
      RouterDigui(payload);
      this.routeList = payload;
    }
    

  },

  persist: {
    key: 'menu', // 自定义存储键名
    storage: localStorage, // 使用 sessionStorage 而非 localStorage
    paths: ['isCollapse', 'selectMenu','routeList'], // 只持久化部分状态
    beforeRestore: (ctx) => {
      console.log('即将恢复状态', ctx)
    },
    afterRestore: (ctx) => {
      console.log('状态已恢复', ctx)
    }
  }
})